import { defineStore } from 'pinia'

type UserRole = 'tenant' | 'landlord'

interface AuthState {
  isLoggedIn: boolean
  role: UserRole | null
  username: string
  token: string
}

export const useAuthStore = defineStore('auth', {
  state: (): AuthState => ({
    isLoggedIn: false,
    role: null,
    username: '',
    token: ''
  }),
  
  actions: {
    login(payload: { role: UserRole; username: string; token: string }) {
      this.isLoggedIn = true
      this.role = payload.role
      this.username = payload.username
      this.token = payload.token
      
      // 持久化存储
      uni.setStorageSync('auth', JSON.stringify(this.$state))
    },
    
    logout() {
      this.$reset()
      uni.removeStorageSync('auth')
      uni.reLaunch({ url: '/pages/login/index' })
    }
  },
  
  // 初始化时从存储加载
  hydrate() {
    const savedState = uni.getStorageSync('auth')
    if (savedState) {
      this.$state = JSON.parse(savedState)
    }
  }
})